<?php
namespace app\index\controller;
use app\index\controller\Base;
class Order extends Base
{   
    public function index(){
        $user=$this->getLoginUser();
        if(!$user){
            $this->error("请登录",url("user/login"));
        }
       // $data=input("get.");
       // print_r($data);exit;
        
       $id=input("get.id",0,"intval");
       if(!$id){
           $this->error("参数不合法");
       }
       $dealCount=input("get.deal_count",0,"intval");
       $totalPrice=input("get.total_price",'',"intval");
       //print_r($totalPrice);exit();
       $deal=model("Deal")->find($id);
        //dump($deal);exit;
        if(!$deal || $deal->status !=1){
            $this->error("商品不合法");
        }
        
        if(empty($_SERVER["HTTP_REFERER"])){
            $this->error("请求非法");
        }
        $tradeSn= setOrderSn();
        //print_r($tradeSn);exit;
       //组装数据
       $data=[
           "out_trade_no"=>$tradeSn,
           "user_id"=>$user->id,
           "username"=>$user->username,
           "deal_id"=>$id,
           "deal_count"=>$dealCount,
           "total_price"=>$totalPrice,
           "referer"=>$_SERVER["HTTP_REFERER"],
       ];
       //对 deal更新
       model("Deal")->save(["buy_count"=>$dealCount],["id"=>$id]);
       
    try{
        $orderId=model("Order")->add($data);
         }catch(\Exception $e){
             $this->error("订单处理出错");
        }
        
        
        //跳转到支付页面
        // print_r($orderId);exit;
        $this->redirect(url("pay/index",['id'=>$orderId]));
        
        
    }
    
     public function confirm(){
        if(!$this->getLoginUser()){
            $this->error("请登录",url('user/login'));
        }
        
        //传入数据以及商品数量
        $id=input("get.id",0 ,"intval");
        if(!$id){
            $this->error("参数不合法");
        }
        $count=input("get.count",1,"intval");
         //传入商品数据
        //print_r($id);exit;
        $deal=model("Deal")->find($id);
        if(!$deal || $deal->status !=1){
            $this->error("商品不合法");
        }
        //dump($deal);exit;
        $deals=$deal->toArray();
        //dump($deals);exit;
        return $this->fetch('',[
            'controler'=>'pay',
            'count'=>$count,
            'deals'=>$deals,
        ]);
    }
    
    
    
    
}


